import json
import os
import base64
from PIL import Image
from pathlib import Path

BASE_PATH = f"C:\\Users\\haoxi\\Desktop\\新表情包素材"


def get_har_files_pathlib(directory):
    # 递归搜索所有 .har 文件
    return list(Path(directory).rglob('*.har'))

def create_dir_if_not_exists(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)  # 创建多级目录（如 a/b/c）
        print(f"目录 {directory} 已创建")
    else:
        print(f"目录 {directory} 已存在")


def main():

    # 示例用法
    har_files = get_har_files_pathlib(BASE_PATH)
    print("找到 .har 文件：",har_files)
    for file in har_files:
        # 创建文件夹
        img_dir = BASE_PATH +"\\"+ file.stem
        create_dir_if_not_exists(img_dir)

        # 指定JSON文件路径
        try:
            # 读取JSON文件
            with open(file, 'r', encoding='utf-8') as f:
                json_data = json.load(f)

            # 检查JSON类型并处理
            if isinstance(json_data, dict):
                parse_json_object(json_data,img_dir)
            elif isinstance(json_data, list):
                parse_json_array(json_data)
            else:
                print("不支持的JSON类型")

        except Exception as e:
            print(f"解析JSON文件时出错: {str(e)}")
            import traceback
            traceback.print_exc()
        finally:
            # 删除JSON文件
            if os.path.exists(file):
                os.remove(file)



# 解析JSON对象
def parse_json_object(json_obj,img_dir : str):
    material_names = []
    for field_name, field_value in json_obj.items():
        if field_name == "text":
            file_name = f"{hash(field_value)}.webp"
            if file_name not in material_names:
                save_base64_as_image(f"data:image/webp;base64,{field_value}", os.path.join(img_dir, file_name))
                material_names.append(file_name)

        # 递归处理子对象
        if isinstance(field_value, dict):
            parse_json_object(field_value,img_dir)
        elif isinstance(field_value, list):
            parse_json_array(field_value,img_dir)


# 解析JSON数组
def parse_json_array(json_array,img_dir:str):
    for item in json_array:
        if isinstance(item, dict):
            parse_json_object(item,img_dir)
        elif isinstance(item, list):
            parse_json_array(item)


# 获取JsonNode类型描述（用于调试）
def get_json_node_type(node):
    if isinstance(node, dict):
        return "对象"
    elif isinstance(node, list):
        return "数组"
    elif isinstance(node, str):
        return "字符串"
    elif isinstance(node, (int, float)):
        return "数字"
    elif isinstance(node, bool):
        return "布尔值"
    elif node is None:
        return "null"
    return "未知类型"


# 将Base64编码的字符串转换为图片并保存到指定路径
def save_base64_as_image(base64_image, file_path):
    # 确保目录存在
    os.makedirs(os.path.dirname(file_path), exist_ok=True)

    # 检查Base64字符串是否包含数据前缀
    if base64_image.startswith("data:"):
        comma_index = base64_image.index(',')
        if comma_index != -1:
            base64_image = base64_image[comma_index + 1:]

    # 解码Base64字符串
    image_bytes = base64.b64decode(base64_image)

    # 保存图片到文件
    with open(file_path, 'wb') as f:
        f.write(image_bytes)
        print("已保存图片：" + file_path)

    with Image.open(file_path) as img:
        # 检查图片模式
        if img.mode == 'RGBA' or img.mode == 'LA' or (img.mode == 'P' and 'transparency' in img.info):
            # 获取alpha通道
            if img.mode == 'RGBA':
                alpha = img.getchannel('A')
                # 检查是否有任何像素的alpha值小于255
                if min(alpha.getdata()) < 255:
                    os.remove(file_path)
                    print("删除图片：" + file_path)
            elif img.mode == 'P':
                # 检查是否有透明调色板项
                transparency = img.info.get('transparency')
                if transparency is not None:
                    # 检查是否有任何像素使用透明调色板项
                    pixels = img.getdata()
                    if transparency in pixels:
                        os.remove(file_path)
                        print("删除图片：" + file_path)



if __name__ == "__main__":
    main()
